/**
 * Created by Administrator on 2017/6/29 0029.
 */
"use strict";

angular.module('app.yksensor').controller('YKDataCtrl', function ($scope, $interval,$http) {
    $scope.current = { pid: ""};
    $scope.changeP = function(){
        // console.log('current projectid is '+$scope.current.pid)
        sends()
    }
    $http.get(baseurls+"/select_idname/project").then(function(res1){
        // console.log(res1.data)
        if(res1.data.ret == 1){
            $scope.projects = res1.data.info;
        }
    })
    
    // var realdata = [];
    var sends = function () {
        var realdata = [];
        $http.post(baseurls+"/actual_data/8052?projectid=="+$scope.current.pid).then(function(res){
            // console.log(res.data);
            if(res.data.ret == 1){
                
                realdata = res.data.info;
                for(var i=0;i<realdata.length;i++){
                    realdata[i].order = i+1;//序号
                    if(realdata[i].sensor_num == 12){//温度计
                        var temps = realdata[i].value.replace("[","").replace("]","").split(",");
                        for(var j=0;j<temps.length;j++){
                            temps[j] = parseFloat(temps[j])/Math.pow(10,realdata[i].point_num);
                            if(temps[j] != 0){
                                if(realdata[i].dm == 1) temps[j] = -temps[j];
                            }
                        }
                        // console.log(temps);
                        realdata[i].value = "["+temps.join("，")+"] °C";
                        // console.log(realdata[i].value);
                    }else if(realdata[i].sensor_num == 1){//液位计
                        var pos = realdata[i].value.replace("[","").replace("]","");
                        pos = parseFloat(pos)/Math.pow(10,realdata[i].point_num);
                        if(pos!=0){
                            if(realdata[i].dm == 1) pos = -pos;
                        }
                        realdata[i].value = ""+pos.toString()+" m3";
                    }else if(realdata[i].sensor_num == 2){//流量计
                        var flow = realdata[i].value.replace("[","").replace("]","").split(",");
                        for(var f=0;f<flow.length;f++){
                            flow[f] = parseFloat(flow[f])/Math.pow(10,realdata[i].point_num);
                            if(flow[f] != 0){
                                if(realdata[i].dm == 1) flow[f] = -flow[f];
                            }
                        }
                        realdata[i].value = "瞬时："+flow[0].toFixed(2)+" m3/s，"+"累计："+flow[1].toFixed(2)+" m3/s";
                    }
                }
            }
            $scope.realdata = realdata;
            // console.log(realdata);
        })
        
        
        
    }
    sends();
    
    var timeout_socket = $interval(sends, 3000);

    $scope.$on('$destroy', function () {
        $interval.cancel(timeout_socket);
    })
	   
	   
	   
    $scope.viewchart = function (deviceid,charttype) {
    
        var base = document.getElementsByTagName("base");
        
        window.location.href = base[0].href + "#/yk_sensorcharts/"+deviceid+"/"+charttype;

    }
		 
	$scope.viewmoredata = function (deviceid) {
       
        var base = document.getElementsByTagName("base");
        
        window.location.href = base[0].href + "#/yk_historicaldata/"+deviceid;

    }

});

//地图
angular.module('app.yksensor').controller('MapCtrl', function ($scope,$interval,$http) {
    $http.get(baseurls+"/list_nopage/device").then(function(res){
        // console.log(res.data);
        //标注点数组
        // var markerArr = [{ title: "西安交通大学", content: "运行良好", point: "108.989137|34.252961", isOpen: 1, icon: { w: 23, h: 25, l: 23, t: 21, x: 9, lb: 12 } } ,{ title: "我的测试", content: "测试content", point: "108.906924|34.354112", isOpen: 0, icon: { w: 23, h: 25, l: 46, t: 21, x: 9, lb: 12 }}];
        if(res.data.ret == 1){
            myMap(res.data.info);
        }
    })
    var markerArr = [];
    function myMap(data) {
        
        // console.log(data);
        for (var j = 0, len = data.length; j < len; j++) {
            var style = "", status = "", icon={}, devicetype="";
            if(data[j].status == 0){
                style = "#f00";
                status = "报警";
                icon = { w: 23, h: 25, l: 46, t: 21, x: 9, lb: 12 };
            }else{
                style = "#00f";
                status = "运行正常";
                icon = { w: 23, h: 25, l: 23, t: 21, x: 9, lb: 12 };
            }
            if(data[j].type = 1) devicetype = "流量计"
            else if(data[j].type = 2) devicetype = "液位计"
            else if(data[j].type = 3) devicetype = "温度计"
            else if(data[j].type = 4) devicetype = "其他"
            
            var content = '<div style="margin:0;line-height:20px;padding:2px;">' +
                    '<hr style="margin:3px 0">'+
                    '客户名称：'+data[j].clientname+'</br>'+
                    '设备名称：'+data[j].devicename+'【'+data[j].deviceid+'】</br>'+
                    '设备状态：<span style="color:'+style+'">'+status+'</span></br>'+
                    '设备类型：'+devicetype+'</br>'+
                '</div>';
            var m = { 
                title: data[j].deviceid,
                content: content,
                point: data[j].pos,
                icon: icon
            };
            
            markerArr.push(m);
        }

        // console.log(markerArr)
        // addMarker();
        initMap();
    }

    // 百度地图API功能

    //创建和初始化地图函数：
    function initMap() {
        createMap();//创建地图
        setMapEvent();//设置地图事件
        addMapControl();//向地图添加控件
        addMarker();//向地图中添加marker
    }

    //创建地图函数：
    function createMap() {
        var map = new BMap.Map("allmap");//在百度地图容器中创建一个地图
        var point = new BMap.Point(108.946306, 34.347436);//定义一个中心点坐标
        map.centerAndZoom(point, 6);//设定地图的中心点和坐标并将地图显示在地图容器中
        window.map = map;//将map变量存储在全局
    }

    //地图事件设置函数：
    function setMapEvent() {
        map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
        map.enableScrollWheelZoom();//启用地图滚轮放大缩小
        map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
        map.enableKeyboard();//启用键盘上下左右键移动地图
    }

    //地图控件添加函数：
    function addMapControl() {
        //向地图中添加缩放控件
        var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE });
        map.addControl(ctrl_nav);
        //向地图中添加缩略图控件
        var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 1 });
        map.addControl(ctrl_ove);
        //向地图中添加比例尺控件
        var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT });
        map.addControl(ctrl_sca);
    }
    
    //创建marker
    function addMarker() {
        for (var i = 0; i < markerArr.length; i++) {
            var json = markerArr[i];
            var p0 = json.point.split("|")[0];
            var p1 = json.point.split("|")[1];
            var point = new BMap.Point(p0, p1);
            var iconImg = createIcon(json.icon);
            var marker = new BMap.Marker(point, { icon: iconImg });
            var iw = createInfoWindow(i);
            var label = new BMap.Label(json.title, { "offset": new BMap.Size(json.icon.lb - json.icon.x + 10, -20) });
            
            marker.setLabel(label);
            
            map.addOverlay(marker);
            label.setStyle({
                borderColor: "#808080",
                color: "#333",
                cursor: "pointer"
            });

            (function () {
                var index = i;
                var _iw = createInfoWindow(i);
                var _marker = marker;
                _marker.addEventListener("click", function () {
                    this.openInfoWindow(_iw);
                });
                _iw.addEventListener("open", function () {
                    _marker.getLabel().hide();
                })
                _iw.addEventListener("close", function () {
                    _marker.getLabel().show();
                })
                label.addEventListener("click", function () {
                    _marker.openInfoWindow(_iw);
                })
                if (!!json.isOpen) {
                    label.hide();
                    _marker.openInfoWindow(_iw);
                }
            })()
        }
    }
    //创建InfoWindow
    function createInfoWindow(i) {
        var json = markerArr[i];
        var iw = new BMap.InfoWindow("<b class='iw_poi_title' title='" + json.title + "'>" + json.title + "</b><div class='iw_poi_content'>" + json.content + "</div>");
        return iw;
    }
    //创建一个Icon
    function createIcon(json) {
        var icon = new BMap.Icon("styles/img/us_mk_icon.png", new BMap.Size(json.w, json.h), { imageOffset: new BMap.Size(-json.l, -json.t), infoWindowOffset: new BMap.Size(json.lb + 5, 1), offset: new BMap.Size(json.x, json.h) })
        return icon;
    }

    // initMap();//创建和初始化地图
})
